package timesheet.repository;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import timesheet.model.Badging;
import timesheet.model.Users;

@Repository
@SuppressWarnings("unchecked")
public class BadgingRepository {
	@PersistenceContext
    EntityManager em;
	
	
	public void createEvent(Badging b) {
		em.persist(b);
	}
	
	
	public void merge(Badging b) {
		em.merge(b);
	}
	
	public void detacheEntity(Badging b) {
		em.detach(b);
	}
	
	public void remove(Badging b) {
		em.remove(b);
	}
	
	public Badging find(Long id){
		return em.find(Badging.class, id);
	}
	
	public List<Badging> getAllBadging() {
		List<Badging> badgingList = em.createQuery("select b from Badging b ORDER BY b.start")
         .getResultList();
    return badgingList;     
	}
	
	public List<Badging> getAllByUser(Users u) {
		List<Badging> badgingList = em.createQuery("select b from Badging b where b.u = :u").setParameter("u", u)
         .getResultList();
    return badgingList;     
	}
	
	public Badging getLastBadgingTimeByUser(Users u) {
//		List<Badging> badgingList = em.createQuery("select MAX(b.id) from Badging b where b.u = :u")
//		 .setParameter("u", u);
//         .getSingleOrNullResult(query);
			 Query query = em.createQuery("select MAX(b.id) from Badging b where b.u = :u").setParameter("u", u);
	         Long id = getSingleOrNullResult(query);
	         if(id!=null){
		         Badging b = em.find(Badging.class, id);
		         return b;   
	         }
	         else{return null;}
	}
	
//	public List<Event> getUserEvent(Long section){
//		String user = String.valueOf(section);
//		List<Event> EventList = em.createQuery("select e from Event e where e.sectionId = :user ORDER BY e.startTime")
//				  				  .setParameter("user", user)
//				  				  .getResultList();
//		return EventList;
//	}
	
	public List<Badging> getAllBadgingByDate(Date from, Date to, String condition){
		List <Badging> list = em.createQuery("select b from Badging b where b.start >= :from and b.start<= :to "+condition+" ORDER BY b.u.id").setParameter("from", from).setParameter("to", to).getResultList();
		return list;
	}
	
	protected Long getSingleOrNullResult(Query query) {
        try {
            Long result = (Long)query.getSingleResult();
            return result;
        } catch (NoResultException nre) {
            return null;  // Normal, entity is just not found.
        }
    }
}
